package com.kakarote.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.kakarote.admin.common.AdminCodeEnum;
import com.kakarote.admin.entity.BO.AdminPageApplyBO;
import com.kakarote.admin.entity.BO.AdminSaveApplyBO;
import com.kakarote.admin.entity.PO.AdminDept;
import com.kakarote.admin.entity.PO.AdminUser;
import com.kakarote.admin.entity.PO.AdminUserApply;
import com.kakarote.admin.mapper.AdminUserApplyMapper;
import com.kakarote.admin.service.*;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.entity.UserInfo;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.UserCacheUtil;
import com.kakarote.core.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 员工申请加入企业历史表 服务实现类
 * </p>
 *
 * @author zhangzhiwei
 * @since 2021-11-06
 */
@Service
public class AdminUserApplyServiceImpl extends BaseServiceImpl<AdminUserApplyMapper, AdminUserApply> implements IAdminUserApplyService {

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private IAdminDeptService adminDeptService;



    @Autowired
    private IAdminUserConfigService adminUserConfigService;

    @Autowired
    private IAdminUserRoleService adminUserRoleService;

    @Override
    public void addUserApply(AdminSaveApplyBO applyBO) {
        AdminUserApply adminUserApply = BeanUtil.copyProperties(applyBO, AdminUserApply.class);
        if (StrUtil.length(adminUserApply.getPassword()) > 20) {
            throw new CrmException(AdminCodeEnum.ADMIN_PASSWORD_INTENSITY_ERROR);
        }
        AdminUserApply userApply = lambdaQuery().eq(AdminUserApply::getPhone, applyBO.getPhone())
                .ne(AdminUserApply::getStatus, 3).one();
        if (userApply == null) {
            adminUserApply.setCreateTime(LocalDateTimeUtil.now());
            adminUserApply.setUpdateTime(LocalDateTimeUtil.now());
            adminUserApply.setStatus(2);
            save(adminUserApply);
        } else {
            if (userApply.getUserId() != null) {
                throw new CrmException(AdminCodeEnum.ADMIN_USER_EXIST_ERROR);
            }
            boolean exists = adminUserService.lambdaQuery().eq(AdminUser::getUsername, applyBO.getPhone()).exists();
            if (exists) {
                throw new CrmException(AdminCodeEnum.ADMIN_USER_EXIST_ERROR);
            }
            adminUserApply.setId(userApply.getId());
            adminUserApply.setUpdateTime(LocalDateTimeUtil.now());
            adminUserApply.setStatus(2);
            updateById(adminUserApply);
        }
    }

    @Override
    public BasePage<JSONObject> queryPageByStatus(AdminPageApplyBO applyBO) {
        BasePage<AdminPageApplyBO> userBasePage = new BasePage<>(applyBO.getPage(), applyBO.getLimit());
        return baseMapper.queryUserList(userBasePage, applyBO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkUserApply(AdminSaveApplyBO applyBO) {
        lambdaUpdate().set(AdminUserApply::getStatus, applyBO.getStatus()).in(AdminUserApply::getId, applyBO.getIds()).update();
        if (applyBO.getStatus() == 1) {
            for (Integer id : applyBO.getIds()) {
                AdminUserApply userApply = getById(id);
                AdminUser adminUserPO = BeanUtil.copyProperties(userApply, AdminUser.class);
                String salt = IdUtil.fastSimpleUUID();
                adminUserPO.setCreateTime(LocalDateTimeUtil.now());
                adminUserPO.setNum(RandomUtil.randomNumbers(15));
                adminUserPO.setMobile(userApply.getPhone());
                adminUserPO.setSalt(salt);
                AdminDept adminDept = adminDeptService.lambdaQuery().eq(AdminDept::getParentId, 0).one();
                adminUserPO.setDeptId(adminDept.getDeptId());
                adminUserPO.setUsername(userApply.getPhone());
                adminUserPO.setPassword(UserUtil.sign((userApply.getPhone().trim() + userApply.getPassword().trim()), salt));

                adminUserService.save(adminUserPO);
                adminUserConfigService.initUserConfig(adminUserPO.getUserId());
                adminUserRoleService.saveByUserId(adminUserPO.getUserId());
                lambdaUpdate().set(AdminUserApply::getExamineUserId, UserUtil.getUserId())
                        .set(AdminUserApply::getUserId, adminUserPO.getUserId())
                        .eq(AdminUserApply::getId, id).update();
            }
        }
    }

    @Override
    public void deleteUserApply(AdminSaveApplyBO applyBO) {
        lambdaUpdate().set(AdminUserApply::getStatus, 3).in(AdminUserApply::getId, applyBO.getIds()).update();
    }

    @Override
    public JSONObject queryJsonByUserId(Long userId) {
        UserInfo userInfo = UserCacheUtil.getUserInfo(userId);
        JSONObject json = new JSONObject();
        json.put("userName", userInfo.getRealname());
        json.put("companyName", userInfo.getCompanyName());
        return json;
    }
}
